﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices;
//using System.DirectoryServices.AccountManagement;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace UserAuthentication
{
    public partial class ChangePassword : Form
    {
        private string _strDomainName = string.Empty;
        private string _strUserLoginName = string.Empty;

        public ChangePassword()
        {
            InitializeComponent();
        }

        public void SetUserName(string strDomainName, string strUserLoginName)
        {
            _strDomainName = strDomainName;
            _strUserLoginName = strUserLoginName;

            if (string.IsNullOrEmpty(strDomainName) == false && string.IsNullOrEmpty(strUserLoginName) == false)
                textBoxUserName.Text = string.Format(@"{0}\{1}", strDomainName, strUserLoginName);
            else
            {
                MessageBox.Show("No valid user!");

                buttonChange.Enabled = false;
            }
        }

        public void SetOldPassword(string strPassword)
        {
            textBoxOldPassword.Text = strPassword;

            if (string.IsNullOrEmpty(strPassword))
                textBoxOldPassword.Focus();
            else
                textBoxNewPassword.Focus();
        }

        public bool ChangeUserPassword()
        {
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            string strEntry = @"LDAP://" + _strDomainName;
            DirectoryEntry objDirectoryEntry = null;
            DirectorySearcher objDirectorySearcher = null;

            try
            {
                objDirectoryEntry = new DirectoryEntry(strEntry);
                objDirectorySearcher = new DirectorySearcher(objDirectoryEntry);
                objDirectorySearcher.Filter = "sAMAccountName=" + _strUserLoginName;
                objDirectorySearcher.SearchScope = SearchScope.Subtree;
                objDirectorySearcher.PropertiesToLoad.Add("cn");

                SearchResult myresult = objDirectorySearcher.FindOne();
                if (myresult == null)
                {
                    MessageBox.Show(string.Format(@"user ({0}) doesn't exist", textBoxUserName.Text));
                    return false;
                }
                else
                {
                    DirectoryEntry userEntry = myresult.GetDirectoryEntry();
                    object[] objPassword = new object[] { textBoxOldPassword.Text.Trim(), textBoxNewPassword.Text.Trim() };
                    object ret = userEntry.Invoke("ChangePassword", objPassword);
                    userEntry.CommitChanges();
                    MessageBox.Show(string.Format(@"Password is changed for user ({0})", textBoxUserName.Text));
                    return true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("exception message - {0}", ex.Message));
                //strComments = @"No rights to browse Active Directory";
                return false;
            }
            finally
            {
                Cursor.Current = currentCursor;
            }
        }

        //public void ChangePassword(string oldPassword, string newPassword)
        //{
        //    try
        //    {
        //        using (var context = new PrincipalContext(ContextType.Domain))
        //        using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userNameWithoutDomain))
        //        {
        //            user.ChangePassword(oldPassword, newPassword);
        //        }

        //    }
        //    catch (Exception ex)
        //    { }
        //}

        private void buttonChange_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxNewPassword.Text))
            {
                MessageBox.Show("New password cannot be empty!");
                textBoxNewPassword.Focus();
                return;
            }
            if (string.IsNullOrEmpty(textBoxOldPassword.Text))
            {
                MessageBox.Show("Old password cannot be empty!");
                textBoxOldPassword.Focus();
                return;
            }
            if (textBoxNewPassword.Text.Equals(textBoxNewPassword2.Text, StringComparison.CurrentCulture) == false)
            {
                MessageBox.Show("The two specified new passwords are not identical!");
                textBoxNewPassword2.Focus();
                return;
            }

            ChangeUserPassword();
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ChangePassword_Load(object sender, EventArgs e)
        {
        }

        private void ChangePassword_Shown(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_strDomainName) || string.IsNullOrEmpty(_strUserLoginName))
            {
                buttonChange.Enabled = false;
                return;
            }

            if (string.IsNullOrEmpty(textBoxOldPassword.Text))
            {
                textBoxOldPassword.Focus();
            }
            else
            {
                textBoxNewPassword.Focus();
            }
        }
    }
}
